<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Api\BaseinitController;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
class ApiController extends BaseinitController
{
    /**
    *小程序部分
    */
    private function httpRequest($url,$data = null){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
    public function openid(Request $request){
        if(!empty($request->input('code'))){
            $code=$request->input('code');

            $url="https://api.weixin.qq.com/sns/jscode2session?appid=wx21773bffcb59059e&secret=2bb52d86a72a9da3d3bc628b2029b7c3&js_code=".$code."&grant_type=authorization_code";
            $res=$this->httpRequest($url);
            if($res){
                $data = [
                    'code' => 200,
                    'msg'   => '请求成功！',
                    'data'  => json_decode($res)
                ];
                return response()->json($data);
            }else{
                $data = [
                    'code' => 500,
                    'msg'   => '请求失败！',
                    'data'  => false
                ];
                return response()->json($data);
            }
        }else{
            $data = [
                'code' => 501,
                'msg'   => 'code缺失',
                'data'  => false
            ];
            return response()->json($data);
        }
    }
    public function updateUserinfo(Request $request){
        $openid=$request->input('openid');
        $nickName=$request->input('nickName');
        $avatarUrl=$request->input('avatarUrl');
        $exit=DB::table('users')->where('openid',$openid)->first();
        if($exit){
            $ok=DB::table('users')->where('openid',$openid)->where('id',$exit->id)->update(['nickName'=>$nickName,'avatarUrl'=>$avatarUrl,'uptime'=>time()]);
            if($ok){
                $data = [
                    'code' => 201,
                    'msg'   => '更新成功',
                ];
            }else{
                $data = [
                    'code' => 501,
                    'msg'   => '更新失败',
                ];
            }
        }else{
            $insertArr=[
                'openid' => $openid,
                'nickName' =>$nickName,
                'avatarUrl' =>$avatarUrl,
                'time' =>time(),
                'uptime' =>time()
            ];
            $ok=DB::table('users')->insert($insertArr);
            if($ok){
                $data = [
                    'code' => 200,
                    'msg'   => '注册成功',
                ];
            }else{
                $data = [
                    'code' => 500,
                    'msg'   => '注册失败',
                ];
            }
        }
        return response()->json($data);
    }
	public function index()
	{
        $openid=$request->input('openid');
        $pageNum=$request->input('page');
        $limit=$request->input('limit');
        $page=$pageNum-1;
        if ($page != 0) {
            $page = $limit * $page;
        }
        $users = DB::table('order')
            ->whereRaw("concat(`teacher`,`account`) like '%".$key."%'")
            ->where($map)
            ->orderBy('id','desc')
            ->offset($page)
            ->take($limit)
            ->get();
        $data = [
            'code' => 0,
            'msg'   => '正在请求中...',
            'count' => $count,
            'data'  => $orders
        ];
        return response()->json($data);
	}
    public function teacherUp()
    {
        $teacher =DB::table('teacher')
            ->where('state',1)
            ->where('recommend',1)
            ->orderBy('uptime','desc')
            ->take(4)
            ->get();
        $data = [
            'code' => 0,
            'msg'   => '正在请求中...',
            'data'  => $teacher
        ];
        return response()->json($data);
    }
	public function courseUp(Request $request)
	{
        $openid=$request->input('openid');
        $course =DB::table('course')
            ->leftJoin('teacher', 'course.t_id', '=', 'teacher.id')
            ->leftJoin('orders', 'course.id', '=', 'orders.course_id')
            ->leftJoin('users', 'orders.user_id', '=', 'users.id')
            ->where('course.state',1)
            ->where('course.recommend',1)
            ->orderBy('course.uptime','desc')
            ->take(4)
            ->select('course.*', 'teacher.teacher', 'teacher.account', 'orders.openid', 'orders.state as isJoined')
            ->get();
        foreach ($course as $key => $value) {
            if($course[$key]->openid==$openid){
                $course[$key]->isJoined=2;
                $course[$key]->openid='';
            }else{
                $course[$key]->isJoined=1;
                $course[$key]->openid='';
            }
            // $course[$key]->detail=mb_substr($course[$key]->detail,0,32);
        }
        $data = [
            'code' => 0,
            'msg'   => '正在请求中...',
            'data'  => $course
        ];
        return response()->json($data);
	}
	public function courseSear()
	{
		$pageNum=$request->input('page');
        $limit=$request->input('limit');
        $page=$pageNum-1;
        if ($page != 0) {
            $page = $limit * $page;
        }
        $course =DB::table('course')
            ->leftJoin('teacher', 'course.t_id', '=', 'teacher.id')
            ->whereRaw("concat(`course`,`account`,`teacher`) like '%".$key."%'")
            ->where($map)
            ->orderBy('course.id','desc')
            ->offset($page)
            ->take($limit)
            ->select('course.*', 'teacher.teacher', 'teacher.account')
            ->get();
        $data = [
            'code' => 0,
            'msg'   => '正在请求中...',
            'count' => $count,
            'data'  => $course
        ];
        return response()->json($data);
	}
    public function incomeUp(Request $request)
    {
        $openid=$request->input('openid');
        $gp_code=$request->input('gp_code');
        $code_name=$request->input('code_name');
        $start_date=$request->input('start_date');
        $end_date=$request->input('end_date');
        $operations=$request->input('operations');
        $income=$request->input('income');
        $exit=DB::table('incomes')->where('openid',$openid)->where('time','>',time()-30)->first();
        if($exit){
            $data = [
                'code' => 501,
                'msg'   => '不要频繁提交',
            ];
        }else{
            $insertArr=[
                'openid' => $openid,
                'gp_code' =>$gp_code,
                'code_name' =>$code_name,
                'start_date' =>$start_date,
                'end_date' =>$end_date,
                'operations' =>$operations,
                'income' =>$income,
                'time' =>time()
            ];
            $ok=DB::table('incomes')->insert($insertArr);
            if($ok){
                $data = [
                    'code' => 200,
                    'msg'   => '保存成功',
                ];
            }else{
                $data = [
                    'code' => 500,
                    'msg'   => '失败',
                ];
            }
        }
        return response()->json($data);
    }
    public function codeIn(Request $request){
        $codearr=$request->input('codearr');
        foreach ($codearr as $key => $value) {
            $insertArr=[
                'code' =>$value['f12'],
                'code_num' =>$value['f12'],
                'code_name' =>$value['f14']
            ];
            $ok=DB::table('code')->insert($insertArr);
        }
        $data = [
            'code' => 200,
            'msg'   => '成功',
        ];
        return response()->json($data);
    }
    public function codePage(Request $request)
    {
        $pageNum=$request->input('page');
        $limit=$request->input('limit');
        $page=$pageNum-1;
        if ($page != 0) {
            $page = $limit * $page;
        }
        $res = DB::table('code')
            ->orderBy('code','asc')
            ->offset($page)
            ->take($limit)
            ->get();
        $data = [
            'code' => 0,
            'msg'   => '正在请求中...',
            'count' => $count,
            'data'  => $res
        ];
        return response()->json($data);
    }
    public function dataIn(Request $request){
        $openid=$request->input('openid');
        $state=$request->input('state');//1:挂卖成功一次；2：挂卖失败一次
        $exit=DB::table('users')->where('openid',$openid)->first();
        if($exit){
            if($state==1){
                $ok=DB::table('users')->where('openid',$openid)->where('id',$exit->id)->update(['success_num'=>$exit->success_num+1,'uptime'=>time()]);
                if($ok){
                    $data = [
                        'code' => 200,
                        'msg'   => '更新成功',
                    ];
                }else{
                    $data = [
                        'code' => 501,
                        'msg'   => '更新失败',
                    ];
                }
            }elseif($state==2){
                $ok=DB::table('users')->where('openid',$openid)->where('id',$exit->id)->update(['fail_num'=>$exit->fail_num+1,'uptime'=>time()]);
                if($ok){
                    $data = [
                        'code' => 200,
                        'msg'   => '更新成功',
                    ];
                }else{
                    $data = [
                        'code' => 502,
                        'msg'   => '更新失败',
                    ];
                }
            }
            
        }else{
            $data = [
                'code' => 201,
                'msg'   => '你是谁？',
            ];
        }
        return response()->json($data);
    }
}